package com.yulang.security.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yulang.security.mobile.SmsSend;
import com.yulang.security.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping
public class CustomController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private SmsSend smsSend;


    public static final String SESSION_KEY = "session_key";

    public static final String MOBILE_SESSION_KEY = "mobile_session_key";

    @RequestMapping("/login")
    public String toLogin() {
        return "/login"; // 会找classpath下面的login.html页面
    }

    @RequestMapping("/mobile/login")
    public String toLoginMobile() {
        return "/login-mobile"; // 会找classpath下面的login.html页面
    }

    @ResponseBody
    @RequestMapping("/code/mobile")
    public Result codeMobile(@RequestParam("mobile") String mobile,HttpServletRequest request) {
        String text = defaultKaptcha.createText();
        request.getSession().setAttribute(MOBILE_SESSION_KEY,text);
        smsSend.send(mobile, text);
        return Result.ok();
    }


    /**
     * 图片验证码生成的接口
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/code/image")
    public void imageCode(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        // 获取验证码字符串
        String text = defaultKaptcha.createText();
        // 放在session中
         request.getSession().setAttribute(SESSION_KEY,text);
        // 获取验证码图片
        BufferedImage image = defaultKaptcha.createImage(text);
        // 把图片写出去
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }

}
